# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - Flask应用初始化
"""

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from config import Config

# 初始化扩展
db = SQLAlchemy()
migrate = Migrate()
jwt = JWTManager()
cors = CORS()


def create_app(config_class=Config):
    """应用工厂函数"""
    app = Flask(__name__)
    app.config.from_object(config_class)
    
    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    cors.init_app(app)
    
    # 注册模板上下文处理器
    @app.context_processor
    def inject_template_functions():
        """注入模板函数"""
        from app.utils.helpers import format_duration
        return {
            'format_duration': format_duration
        }
    
    # 注册蓝图 - 为不同功能模块使用不同的前缀
    # 认证相关API
    from app.api.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    
    # 用户相关API
    from app.api.users import bp as users_bp
    app.register_blueprint(users_bp, url_prefix='/api/users')
    
    # 管理员相关API
    from app.api.admin import bp as admin_bp
    app.register_blueprint(admin_bp, url_prefix='/api/admin')
    
    # 量表相关API
    from app.api.scales import bp as scales_bp
    app.register_blueprint(scales_bp, url_prefix='/api/scales')
    
    # 测评相关API
    from app.api.assessments import bp as assessments_bp
    app.register_blueprint(assessments_bp, url_prefix='/api/assessments')
    
    # 会员相关API
    from app.api.members import bp as members_bp
    app.register_blueprint(members_bp, url_prefix='/api/members')
    
    # 系统相关API
    from app.api.system import bp as system_bp
    app.register_blueprint(system_bp, url_prefix='/api/system')
    
    # 主页面蓝图
    from app.main import bp as main_bp
    app.register_blueprint(main_bp)
    
    # 会员前台页面蓝图
    from app.members import bp as members_frontend_bp
    app.register_blueprint(members_frontend_bp, url_prefix='/members')
    
    # 公开访问蓝图
    from app.public import bp as public_bp
    app.register_blueprint(public_bp, url_prefix='/public')
    
    return app


# 导入模型（避免循环导入）
from app import models